package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.CourseTrainFile;
import com.dingreading.cloud.admin.entity.table.CourseTrainFileTableDef;
import com.dingreading.cloud.admin.mapper.CourseTrainFileMapper;
import com.dingreading.cloud.admin.service.CourseTrainFileService;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 叮叮线下培训课程文件表 服务层实现。
 *
 * @author EDY
 * @since 2025-11-18
 */
@Service
public class CourseTrainFileServiceImpl extends BaseServiceImpl<CourseTrainFileMapper, CourseTrainFile, CourseTrainFileTableDef> implements CourseTrainFileService {

    @Override
    protected CourseTrainFileTableDef getTable() {
        return CourseTrainFileTableDef.courseTrainFile;
    }

    @Override
    public Page<CourseTrainFile> pageFileList(PageUtil pageUtil, String lessonUid, String keyword, Integer enabled) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (StringUtils.isNotBlank(lessonUid))
            condition.and(table.trainUid.eq(lessonUid));

        if (StringUtils.isNotBlank(keyword))
            condition.and(table.name.like(keyword));
        if (enabled != null)
            condition.and(table.enabled.eq(enabled));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.id.asc());

        return getMapper().paginate(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper);
    }

    @Override
    public CourseTrainFile getByUid(String uid) {
        return getMapper().selectOneByCondition(table.uid.eq(uid));
    }

    @Override
    public List<CourseTrainFile> getByLessonUid(String lessonUid) {
        return getMapper().selectListByCondition(table.trainUid.eq(lessonUid));
    }

    @Override
    public Map<String, Integer> getFileVideosDurations(List<String> fileUids) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.fileType.eq(0))
                .and(table.uid.in(fileUids));
        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.uid, table.videoDuration)
                .where(condition);
        return getMapper().selectListByQueryAs(wrapper, CourseTrainFile.class)
                .stream()
                .collect(Collectors.toMap(CourseTrainFile::getUid, CourseTrainFile::getVideoDuration));
    }
}
